package com.us.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.*;

/**
 *   
 * @author yangyibo
 *
 */
public class KafkaConsumerSpec extends Thread{
	private String topic;  
    
    public KafkaConsumerSpec(String topic){
        super();  
        this.topic = topic;  
    }  
      
      
    @Override  
    public void run() {
        KafkaConsumer<String, String> consumer = createConsumer(topic);

        int i=0;
        int b =0 ;
        System.out.println(new Date());
        while(true) {
            b++;
            ConsumerRecords<String, String> msgList = consumer.poll(1000);
            System.out.println("监听循环 - " + b);
            for(ConsumerRecord<String, String> msg : msgList)
            {
                i++;
                System.out.println(new Date());
                System.out.println("value: " + msg.value());
            }
        }

    }
  
    private KafkaConsumer<String, String> createConsumer(String topicname) {
        Properties props = new Properties();

        props.put("bootstrap.servers", "192.168.30.4:9092");
//        props.put("bootstrap.servers", "220.249.116.42:9093");
        props.put("group.id", KafkaConfig.Consumer_groupId);
        props.put("enable.auto.commit", "false");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");
        props.put("max.poll.records", 1000);
        props.put("auto.offset.reset", "earliest");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);
        consumer.subscribe(Arrays.asList("shuaige"));
        return consumer;
    }
      
    /**
     * 
     * @param topicName
     */
    public static void creatConsumer(String topicName) {  // 使用kafka集群中创建好的主题

        new KafkaConsumerSpec(topicName).start();
    }
}  